#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "videoplayer.h"
#include <QFileDialog>
#include <QtDebug>
#include <QLatin1String>
#include <fstream>
#include <QMouseEvent>
#include <QGraphicsOpacityEffect>
#include "volumebutton.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 注册信号的参数类型，保证能够发出信号
    qRegisterMetaType<VideoPlayer::VideoSwsSpec>("VideoSwsSpec&");
    init();
}

MainWindow::~MainWindow()
{
    delete m_player;
    delete ui;
    disconnect();
}

void MainWindow::mousePressEvent(QMouseEvent *event){
    // 保存鼠标按下时的位置和窗口的位置
    if (event->button() == Qt::LeftButton) {
        m_dragStartPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event){
    if (!(event->buttons() & Qt::LeftButton)) {
        return;
    }
    if (m_dragStartPosition.isNull()) {
        return;
    }
    move(event->globalPos() - m_dragStartPosition);
    event->accept();
}

void MainWindow::init(){
    QFile qssFile(":/style/css1.qss");
    ui->sliderWidget->hide();
    //ui->videoWidget->hide();
    qssFile.open(QFile::ReadOnly);
    if(qssFile.isOpen()){
        QString styleSheet = QLatin1String(qssFile.readAll());
        qApp->setStyleSheet(styleSheet);
    }
    recordReadFileName();
    recordReadFilePath();
    loadPlayList();
    m_player = new VideoPlayer(this);
    initBtns();
    //setCentralWidget(ui->top_widget);
    ui->label_current->setStyleSheet("QLabel { color : red; }");
    ui->label_duration->setStyleSheet("QLabel { color : red; }");
    ui->bottom_widget->setStyleSheet("QWidget {background-color:#363738;}");
    ui->top_widget->setStyleSheet("QWidget {background-color:#363738;}");
    ui->listWidget_filename->setStyleSheet("QListWidget {background-color:#363738;}"
                                           "QListWidget::item:selected { background-color: #464748;padding-left:0px;padding-right:0px; }"
                                           "QListWidget::item {padding-left:0px;padding-right:0px;}");
    //setUIParams();
    attchMenuToMoreBtn();
    connect(ui->btn_minimize,&MyPushButton::clicked,this,&MainWindow::onBtnMinimizeClicked);
    connect(ui->btn_maxmize,&MyPushButton::clicked,this,&MainWindow::onBtnMaxMizeClicked);
    connect(ui->btn_close,&MyPushButton::clicked,this,&MainWindow::onBtnCloseClicked);
    connect(ui->btn_menu,&MyPushButton::clicked,this,&MainWindow::onMoreBtnClicked);
    connect(ui->actionvideoFile,&QAction::triggered,this,&MainWindow::onOpenFileActionTriggered);
    connect(m_player,&VideoPlayer::frameDecoded,ui->videoWidget,&VideoWidget::onPlayerFrameDecoded);
    connect(m_player,&VideoPlayer::stateChanged,ui->videoWidget,&VideoWidget::onPlayerStateChanged);
    connect(ui->btn_play,&QPushButton::clicked,this,&MainWindow::onBtnPlayClicked);
    connect(ui->btn_stop,&QPushButton::clicked,this,&MainWindow::onBtnStopClicked);
    connect(m_player,&VideoPlayer::stateChanged,this,&MainWindow::onPlayerStateChanged);
    connect(m_player, &VideoPlayer::initFinished,this,&MainWindow::onPlayerInitFinished);
    connect(m_player,&VideoPlayer::timeChanged,this,&MainWindow::onPlayerTimeChanged);
    connect(ui->currentSlider,&VideoSlider::valueChanged,this,&MainWindow::onCurrentSliderValueChanged);
    connect(ui->currentSlider,&VideoSlider::clicked,this,&MainWindow::onSliderClicked);
    connect(ui->listWidget_filename,&QListWidget::itemDoubleClicked,this,&MainWindow::onFileNameItemDoubleClicked);
    connect(ui->btn_prev,&QPushButton::clicked,this,&MainWindow::onBtnPrevClicked);
    connect(ui->btn_next,&QPushButton::clicked,this,&MainWindow::onBtnNextClicked);
    connect(ui->btn_volume,&VolumeButton::clicked,this,&MainWindow::onBtnVolumeClicked);
    connect(ui->btn_volume,&VolumeButton::volume_changed,m_player,&VideoPlayer::onVolumeChanged);
    connect(ui->btn_Expand,&QPushButton::clicked,this,&MainWindow::onBtnExpandClicked);

}

void MainWindow::onBtnExpandClicked(){
    if(ui->listWidget_filename->isVisible()){
        ui->listWidget_filename->hide();
        ui->btn_Expand->setNormalImage(":/image/normal/expand.png");
        ui->btn_Expand->setHoverImage(":/image/hover/expand.png");
        ui->btn_Expand->setPressImage(":/image/press/expand.png");
    }else{
        ui->listWidget_filename->show();
        ui->btn_Expand->setNormalImage(":/image/normal/collapse.png");
        ui->btn_Expand->setHoverImage(":/image/hover/collapse.png");
        ui->btn_Expand->setPressImage(":/image/press/collapse.png");
    }
}

void MainWindow::onBtnPrevClicked(){
    int index = ui->listWidget_filename->currentRow();
    if(index == 0){
        return;
    }
    --index;
    ui->listWidget_filename->setItemSelected(ui->listWidget_filename->item(index),true);
    ui->listWidget_filename->setCurrentRow(index);
    auto filePath = m_mapFilePath[index+1];
    play(filePath);
}

void MainWindow::onBtnNextClicked(){
    int index = ui->listWidget_filename->currentRow();
    if(index == ui->listWidget_filename->count() - 1){
        return;
    }
    ++index;
    ui->listWidget_filename->setItemSelected(ui->listWidget_filename->item(index),true);
    ui->listWidget_filename->setCurrentRow(index);
    auto filePath = m_mapFilePath[index+1];
    play(filePath);
}

void MainWindow::onBtnVolumeClicked(){
    qDebug() << "onBtnVolumeClicked";
    //点击之后,静音和非静音切换
    m_player->setMute(!m_player->isMute());
    if(m_player->isMute()){
        ui->btn_volume->setNormalImage(":/image/normal/volume_stat0.png");
        ui->btn_volume->setHoverImage(":/image/hover/volume_stat0.png");
        ui->btn_volume->setPressImage(":/image/press/volume_stat0.png");
    }else{
        ui->btn_volume->setNormalImage(":/image/normal/volume_stat2.png");
        ui->btn_volume->setHoverImage(":/image/hover/volume_stat2.png");
        ui->btn_volume->setPressImage(":/image/press/volume_stat2.png");
    }
}

void MainWindow::initBtns(){
    ui->btn_minimize->setNormalImage(":/image/normal/minbtn.png");
    ui->btn_minimize->setHoverImage(":/image/hover/minbtn.png");
    ui->btn_minimize->setPressImage(":/image/press/minbtn.png");

    ui->btn_maxmize->setNormalImage(":/image/normal/maxbtn.png");
    ui->btn_maxmize->setHoverImage(":/image/hover/maxbtn.png");
    ui->btn_maxmize->setPressImage(":/image/press/maxbtn.png");

    ui->btn_close->setNormalImage(":/image/normal/close_btn.png");
    ui->btn_close->setHoverImage(":/image/hover/close_btn.png");
    ui->btn_close->setPressImage(":/image/press/close_btn.png");

    ui->btn_menu->setNormalImage(":/image/normal/more_btn.png");
    ui->btn_menu->setHoverImage(":/image/hover/more_btn.png");
    ui->btn_menu->setPressImage(":/image/press/more_btn.png");

    ui->btn_stop->setNormalImage(":/image/normal/ctrl_stop.png");
    ui->btn_stop->setHoverImage(":/image/hover/ctrl_stop.png");
    ui->btn_stop->setPressImage(":/image/press/ctrl_stop.png");
    ui->btn_stop->setEnabled(false);
    ui->btn_play->setNormalImage(":/image/normal/ctrl_play.png");
    ui->btn_play->setHoverImage(":/image/hover/ctrl_play.png");
    ui->btn_play->setPressImage(":/image/press/ctrl_play.png");
    ui->btn_play->setEnabled(false);

    ui->btn_prev->setNormalImage(":/image/normal/ctrl_prev.png");
    ui->btn_prev->setHoverImage(":/image/hover/ctrl_prev.png");
    ui->btn_prev->setPressImage(":/press/press/ctrl_prev.png");
    ui->btn_prev->setEnabled(false);

    ui->btn_next->setNormalImage(":/image/normal/ctrl_next.png");
    ui->btn_next->setHoverImage(":/image/hover/ctrl_next.png");
    ui->btn_next->setPressImage(":/press/press/ctrl_next.png");
    ui->btn_next->setEnabled(false);

    ui->btn_volume->setNormalImage(":/image/normal/volume_stat2.png");
    ui->btn_volume->setHoverImage(":/image/hover/volume_stat2.png");
    ui->btn_volume->setPressImage(":/image/press/volume_stat2.png");
    ui->btn_volume->setVolume(m_player->getVolumn());
    ui->btn_volume->setMute(m_player->isMute());

    QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect(ui->btn_Expand);
    effect->setOpacity(0.5); // 设置透明度为50%
    ui->btn_Expand->setGraphicsEffect(effect);

    ui->btn_Expand->setNormalImage(":/image/normal/collapse.png");
    ui->btn_Expand->setHoverImage(":/image/hover/collapse.png");
    ui->btn_Expand->setPressImage(":/image/press/collapse.png");

    ui->btn_speedplay->setNormalImage(":/image/normal/bk.png");
    ui->btn_speedplay->setButtonWidth(64);
    ui->btn_speedplay->setButtonHeight(32);
}

void MainWindow::onFileNameItemDoubleClicked(QListWidgetItem* item){
    int index = ui->listWidget_filename->row(item);
    play(m_mapFilePath[index+1]);
}

void MainWindow::onBtnMinimizeClicked(){
    this->showMinimized();
}

void MainWindow::onBtnMaxMizeClicked(){
    if(this->isMaximized()){
        this->showNormal();
        ui->btn_maxmize->setNormalImage(":/image/normal/maxbtn.png");
        ui->btn_maxmize->setHoverImage(":/image/hover/maxbtn.png");
        ui->btn_maxmize->setPressImage(":/image/press/maxbtn.png");
    }else{
        this->showMaximized();
        ui->btn_maxmize->setNormalImage(":/image/normal/restorebtn.png");
        ui->btn_maxmize->setHoverImage(":/image/hover/restorebtn.png");
        ui->btn_maxmize->setPressImage(":/image/press/restorebtn.png");
    }
}

void MainWindow::onBtnCloseClicked(){
    this->close();
}

void MainWindow::setUIParams(){
    //this->statusBar()->setVisible(false);
}

void MainWindow::attchMenuToMoreBtn(){
    QMenuBar* bar = this->menuBar();
    bar->setVisible(false);
    QMenu* fileMenu = bar->findChild<QMenu*>("menu_file");
    ui->btn_menu->setMenu(fileMenu);
}

void MainWindow::onMoreBtnClicked(){

}

void MainWindow::onSliderClicked(VideoSlider *slider){
    m_player->setTime(slider->value());
}

void MainWindow::onPlayerTimeChanged(VideoPlayer* player){
    //qDebug() << player->getTime();
    ui->currentSlider->setValue(player->getTime());
}

void MainWindow::onCurrentSliderValueChanged(int value){

    ui->label_current->setText(getTimeText(value));
}

void MainWindow::onPlayerInitFinished(VideoPlayer *player){
    int duration = player->getDuration();
    qDebug()<<"duration:" << duration << "s";
    // 设置一些slider的范围
    ui->currentSlider->setRange(0,duration);
    // 设置label的文字
    ui->label_duration->setText(getTimeText(duration));
}

void MainWindow::loadPlayList(){
    for(auto iter = m_mapFileName.begin();iter != m_mapFileName.end();++iter){
        ui->listWidget_filename->addItem(QString::fromStdString(iter->second));
    }
}

void MainWindow::play(const QString& fileName){
    if(m_player->getState() != VideoPlayer::Stopped){
        m_player->stop();
    }
    //开始播放打开的文件
    m_player->setFileName(fileName);
    m_player->play();
}

void MainWindow::play(const std::string& fileName){
    QString qFileName = QString::fromStdString(fileName);
    play(qFileName);
}

void MainWindow::onOpenFileActionTriggered(bool checked){
    QString filename = QFileDialog::getOpenFileName(nullptr,"请选择多媒体文件","d:/","多媒体文件(*.mp4 *.rmvb *.avi *.mkv *.mp3 *.aac)");
    qDebug() << "打开文件" << filename;

    play(filename);

    QFileInfo fileInfo(filename);
    ui->listWidget_filename->addItem(fileInfo.fileName());
    ui->listWidget_filename->setItemSelected(ui->listWidget_filename->item(ui->listWidget_filename->count()-1),true);
    m_mapFileName[ui->listWidget_filename->count()] = fileInfo.fileName().toUtf8().constData();
    m_mapFilePath[ui->listWidget_filename->count()] = filename.toUtf8().constData();
    recordWriteFileName();
    recordWriteFilePath();
}

void MainWindow::recordReadFileName(){
    std::ifstream in("filenameList.txt",std::ios::in);
    if(!in.is_open()){
        qDebug() << "打开文件失败" << endl;
        return;
    }
    std::string fileName;
    int index = 0;
    while(!in.eof()){
        fileName.clear();
        in >> fileName;
        if(!fileName.empty()){
            m_mapFileName[++index] = fileName;
        }
    }
    in.close();
}

void MainWindow::recordReadFilePath(){
    std::ifstream in("filepathList.txt",std::ios::in);
    if(!in.is_open()){
        qDebug() << "打开文件失败" << endl;
        return;
    }
    std::string filePath;
    int index = 0;
    while(!in.eof()){
        filePath.clear();
        in >> filePath;
        if(!filePath.empty()){
            m_mapFilePath[++index] = filePath;
        }
    }
    in.close();
}

void MainWindow::recordWriteFileName(){
    std::ofstream out("filenameList.txt",std::ios::out | std::ios::trunc);
    if(!out.is_open()){
        qDebug() << "打开文件失败" << endl;
        return;
    }
    std::string fileName;
    int index = 0;
    //TODO qt的endl和std的endl不是同一个东西
    for(auto iter = m_mapFileName.begin();iter != m_mapFileName.end();++iter){
        out << iter->second.c_str() << "\n";
    }

    out.close();
}

void MainWindow::recordWriteFilePath(){
    std::ofstream out("filepathList.txt",std::ios::out | std::ios::trunc);
    if(!out.is_open()){
        qDebug() << "打开文件失败" << endl;
        return;
    }
    std::string fileName;
    int index = 0;

    for(auto iter = m_mapFilePath.begin();iter != m_mapFilePath.end();++iter){
        out << iter->second.c_str() << "\n";
    }

    out.close();
}

QString MainWindow::getTimeText(int value){
    QString h = QString("0%1").arg(value / 3600).right(2);
    QString m = QString("0%1").arg((value / 60) % 60).right(2);
    QString s = QString("0%1").arg(value % 60).right(2);

    return  QString("%1:%2:%3").arg(h).arg(m).arg(s);
}

void MainWindow::onBtnPlayClicked(){
    //先判断当前是否处于播放状态
    auto state = m_player->getState();
    if(state == VideoPlayer::Playing){
        m_player->pause();
    }else{
        m_player->play();
    }
}

void MainWindow::onBtnStopClicked(){
    m_player->stop();
}

void MainWindow::onPlayerStateChanged(VideoPlayer *player){
    auto state = m_player->getState();
    if(state == VideoPlayer::Playing){
        ui->btn_play->setText("暂停");
        ui->btn_play->setNormalImage(":/image/normal/ctrl_pause.png");
        ui->btn_play->setHoverImage(":/image/hover/ctrl_pause.png");
        ui->btn_play->setPressImage(":/image/press/ctrl_pause.png");
    }else{
        ui->btn_play->setText("播放");
        ui->btn_play->setNormalImage(":/image/normal/ctrl_play.png");
        ui->btn_play->setHoverImage(":/image/hover/ctrl_play.png");
        ui->btn_play->setPressImage(":/image/press/ctrl_play.png");
    }

    if(state == VideoPlayer::Stopped){
        ui->sliderWidget->hide();
        ui->btn_stop->setEnabled(false);
        ui->btn_play->setEnabled(true);
        ui->btn_prev->setEnabled(false);
        ui->btn_next->setEnabled(false);
    }else{
        ui->sliderWidget->show();
        ui->btn_stop->setEnabled(true);
        ui->btn_play->setEnabled(true);
        ui->btn_prev->setEnabled(true);
        ui->btn_next->setEnabled(true);
    }
}
